package com.woniuxy.realm;

import com.woniuxy.pojo.User;
import com.woniuxy.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class RbacRealm extends AuthorizingRealm {
    private Logger logger=Logger.getLogger(this.getClass());
    @Autowired
    private UserService userService;

    @Override
    public String getName() {
        return "rbacRealm";
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.debug("**********授权**************");
        String telephone=(String)principalCollection.getPrimaryPrincipal();
        Set<String> roleNames=this.userService.selectRolesNamesByTelephone(telephone);
        Set<String> permissions = this.userService.selectPerCodesByTelephone(telephone);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roleNames);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.debug("**********认证**************");
        String telephone=(String)authenticationToken.getPrincipal();
        User user=this.userService.selectUserByTelephone(telephone);
        AuthenticationInfo info=new SimpleAuthenticationInfo(telephone,user.getPassword(),this.getName());
        return info;
    }
}
